<script setup lang="ts">
import { nextTick, onMounted, reactive, ref } from "vue";
import JinDrawer from "@/components/framework/jin-drawer/jin-drawer.vue";
import type { FormRule } from "@/types/commonType.ts";
import { FormInstance, Message } from "@arco-design/web-vue";
import useFormSubmit from "@/hooks/useFormSubmit.ts";
import {
  expertAddApi,
  expertEditApi,
  selectListAll,
  listRacetrack,
  listNormalRacetrack,
} from "@/services/expertManagement";
import type {
  ExpertUpdateType,
  OtherChildrenListType,
  ListRacetrackType,
} from "@/types/expertManagement";
import matchRules from "@/utils/Regexp";
const props = defineProps({
  title: String,
  dataType: Number,
});

const formRef = ref<FormInstance>();

const loading = ref(false);

const handleSubmit = useFormSubmit(formRef);

const readOnly = ref<boolean>(false)

const emits = defineEmits<{
  (e: "list"): void;
}>();

const drawer = ref<{
  init: () => void;
  close: () => void;
}>();

const options = reactive({
  title: "",
  type: 0,
});

const formModel = reactive<ExpertUpdateType>({
  id: "",
  name: "", //内容
  trueName: "", //姓名
  phone: "", //手机
  city: "", //城市（字典下拉，参赛项目来源）
  channel: "", //赛道（字典下拉，常规赛道+企业赛道，去重复值）
  unit: "", //单位
  post: "", //职务
  title: '', // 职称
  remark: '' // 备注

});

const rules = reactive<FormRule>({
  name: {
    required: true,
    message: "请输入账号",
  },
  trueName: {
    required: true,
    message: "请输入真实姓名",
  },
  phone: [
    {
      required: true,
      message: "请输入电话",
    },
    {
      match: matchRules.getRegexp("CNphoneRules"),
      message: "手机号格式错误",
    },
  ],
  city: {
    required: true,
    message: "请输入来源",
  },
  channel: {
    required: true,
    message: "请输入领域",
  },
  unit: {
    required: true,
    message: "请输入单位",
  },
  post: {
    required: false,
    message: "请输入职务",
  },
  title: {
    required: false,
    message: "请输入职称",
  }
});

const handleCancel = () => {
  drawer.value?.close();
};

const promise = (url: any, msg: string) => {
  url
    .then((res: any) => {
      if (res.code === 200) {
        Message.success(msg);
        handleCancel();
        emits("list");
      }
    })
    .finally(() => {
      loading.value = false;
    });
};

const handleOk = () => {
  console.log(readOnly.value)
  if (!readOnly.value) {
    loading.value = true;
    const user = JSON.parse(JSON.stringify(formModel));
    if (options.type === 0) {
      delete user.id;
      promise(expertAddApi(user), "新增成功");
    }
    if (options.type === 1) {
      promise(expertEditApi(user), "修改成功");
    }
  } else {
    handleCancel();
  }
};

const show = () => {
  getOptions();
  options.type = 0;
  formModel.id = "";
  formModel.name = "";
  formModel.trueName = "";
  formModel.phone = "";
  formModel.city = "";
  formModel.channel = "";
  formModel.unit = "";
  formModel.post = "";
  formModel.title = "";
  formModel.remark = "";
  drawer.value?.init();
  loading.value = false;
  formRef.value?.clearValidate();
  readOnly.value = false
};

const edit = (data: ExpertUpdateType) => {
  getOptions();
  options.type = 1;
  formModel.id = data.id;
  formModel.name = data.name;
  formModel.trueName = data.trueName;
  formModel.phone = data.phone;
  formModel.city = data.city;
  formModel.channel = data.channel;
  formModel.unit = data.unit;
  formModel.post = data.post;
  formModel.title = data.title;
  formModel.remark = data.remark;
  loading.value = false;
  drawer.value?.init();
  formRef.value?.clearValidate();
  readOnly.value = false
};

const info = (data: ExpertUpdateType) => {
  options.type = 1;
  formModel.id = data.id;
  formModel.name = data.name;
  formModel.trueName = data.trueName;
  formModel.phone = data.phone;
  formModel.city = data.city;
  formModel.channel = data.channel;
  formModel.unit = data.unit;
  formModel.post = data.post;
  formModel.title = data.title;
  formModel.remark = data.remark;
  loading.value = false;
  drawer.value?.init();
  formRef.value?.clearValidate();
  readOnly.value = true
}
const optionsList = ref([]);

const list = reactive<{
  [key: string]: OtherChildrenListType[];
}>({
  参赛项目来源: [],
  赛道: [],
  参赛方式: [],
});

const racetrackList = reactive<{
  s: ListRacetrackType[];
}>({
  s: [],
});
const getOptions = () => {
  selectListAll().then((res) => {
    if (res.code === 200) {
      optionsList.value = res.data;
      for (const key in list) {
        const find = res.data.find((item) => item.dictCode === key);
        if (find) {
          list[key] = find.dictItemList;
        }
      }
      list["参赛项目来源"].unshift({
        createBy: '',
        createTime: "2025-06-25 10:17:23",
        description: "赛道",
        id: "1",
        updateBy: '',
        updateTime: "2025-06-25 10:17:23",
        itemText: "省直",
        itemValue: '省直',
        dictId: '',
        itemColor: '',
        sortOrder: 0,
        status: 0
      })
    }
  });
  //   企业
  listRacetrack().then((res) => {
    if (res.code === 200) {
      // 赛道 常规
      listNormalRacetrack().then((res1) => {
        if (res1.code === 200) {
          // new set() [值，值]数组  new map() [键，值]的形式存储
          const uniqueRacetracks = new Map();
          res.data.forEach((item) => {
            if (!uniqueRacetracks.has(item.dictName)) {
              uniqueRacetracks.set(item.dictName, item);
            }
          });
          res1.data.forEach((item) => {
            if (!uniqueRacetracks.has(item.dictName)) {
              uniqueRacetracks.set(item.dictName, item);
            }
          });
          console.log(uniqueRacetracks)
          racetrackList.s = Array.from(uniqueRacetracks.values());
          racetrackList.s.unshift({
            createBy: '',
            createTime: "2025-06-25 10:17:23",
            delFlag: 0,
            description: "赛道",
            dictCode: "数据领域",
            dictName: "数据领域",
            id: "1",
            type: '0',
            updateBy: '',
            updateTime: "2025-06-25 10:17:23",
          })
          console.log(racetrackList.s);
        }
      });
    } else {
    }
  });
  // 合并两个列表并去重
};

defineExpose({
  show,
  edit,
  info
});
</script>

<template>
  <jin-drawer
    ref="drawer"
    :title="props.title"
    :width="600"
    @ok="handleOk"
    @cancel="handleCancel"
    @beforeOk="handleSubmit"
    :loading="loading"
    :ok-loading="loading"
  >
    <a-form
      auto-label-width
      :model="formModel"
      :rules="rules"
      ref="formRef"
    >
      <a-form-item
        label="账号"
        field="name"
      >
        <a-input
          v-model="formModel.name"
          allow-clear
          v-if="!readOnly"
          placeholder="请输入账号"
        />
        <span v-else>{{ formModel.name }}</span>
      </a-form-item>

      <a-form-item
        label="姓名"
        field="trueName"
      >
        <a-input
          v-model="formModel.trueName"
          allow-clear
          v-if="!readOnly"
          placeholder="请输入姓名"
        />
        <span v-else>{{ formModel.trueName }}</span>
      </a-form-item>

      <a-form-item
        label="电话"
        field="phone"
      >
        <a-input
          v-model="formModel.phone"
          allow-clear
          v-if="!readOnly"
          placeholder="请输入电话"
        />
        <span v-else>{{ formModel.phone }}</span>
      </a-form-item>

      <a-form-item
        label="来源"
        field="city"
      >
        <a-input
            v-model="formModel.city"
            v-if="!readOnly"
            allow-clear
            placeholder="请输入来源"
        />
        <span v-else>{{ formModel.city }}</span>
      </a-form-item>

      <a-form-item
        label="领域"
        field="channel"
      >
        <a-input
            v-model="formModel.channel"
            v-if="!readOnly"
            allow-clear
            placeholder="请输入领域"
        />
        <span v-else>{{ formModel.channel }}</span>
      </a-form-item>

      <a-form-item
        label="单位"
        field="unit"
      >
        <a-input
          v-model="formModel.unit"
          v-if="!readOnly"
          allow-clear
          placeholder="请输入单位"
        />
        <span v-else>{{ formModel.unit }}</span>
      </a-form-item>

      <a-form-item
        label="职务"
        field="post"
      >
        <a-input
          v-model="formModel.post"
          v-if="!readOnly"
          allow-clear
          placeholder="请输入职务"
        />
        <span v-else>{{ formModel.post }}</span>
      </a-form-item>
      <a-form-item
          label="职称"
          field="title"
      >
        <a-input
            v-if="!readOnly"
            v-model="formModel.title"
            allow-clear
            placeholder="请输入职称"
        />
        <span v-else>{{ formModel.title }}</span>
      </a-form-item>
      <a-form-item
          label="备注"
          field="remark"
      >
        <a-textarea
            v-if="!readOnly"
            v-model="formModel.remark"
            allow-clear
            :auto-size="{
              minRows: 6
            }"
            placeholder="请输入备注"
        />
        <span v-else>{{ formModel.remark }}</span>
      </a-form-item>
    </a-form>

    <template #footer>
      <a-button>
        关闭
      </a-button>
    </template>
  </jin-drawer>
</template>

<style scoped lang="scss">
</style>